import {getOrder} from '../../../api/api.js';
import {delOrder} from '../../../api/api.js';
import {waitingPay} from '../../../api/api.js';
import {extendDate2} from '../../utils/order/order';
import {confirmGetGoods2} from '../../utils/order/order';




let app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties:{
     flag:{
        type:String,
        value:''
     }
      
  },

  /**
   * 
   * id;
goodsId;商品id
specName;规格名
commentTime;评论时间
openId;用户id
nikeName;用户昵称
userPic;用户头像
contentType;评论类型 1好评 0差评
merchantId;商品所属商家id
userContent;用户评论内容
pic;评论图片
merchantContent;商家回复内容
comments;所有用户的评论和商家的回复
   * **/ 
  

  /**
   * 组件的初始数据
   */
  data: {
    allOrder: [
       
    ],
    currentPage:2,
    //用来区分订单类型（比如待收货...）
    flag:'',
    // 选择评价的商品弹出框
    show:false,

    // 点击评论的时候选中的item
    selectItem:{}
  },

  /**
   * 组件的方法列表
   */
  methods: {

     
    /**
     *  [{
     *      store:storeName,
            goodsList:[
               {
                  specName,
                  specId,
                  goodsPrice,
                  goodsAmount
               }
            ]
     *  }]


        


     * ***/  



    //去付款页面
    toPay(e){
        console.log("去付款");
        //let storeName = 
        let orderId = e.currentTarget.dataset.order.details[0].orderId;
        console.log(orderId,"去付款方法");
        let orderList = [];
        orderList.push(orderId);
        waitingPay(orderList).then(res=>{
            console.log(res,"待付款付款结果")
            if(res.data.code == 200){
                this.wxPay(res.data.data);
            }else{
                 wx.showToast({
                   title: '支付失败,服务器异常',
                   icon:'none'
                 })
            }
        })

    },


    

   wxPay(data){
    /**
     * "timeStamp": "1584673885",
  "nonce_str": "xcoAuYKU4OYJD6G0",
  "appid": "wxae419779fd57bae0",
  "outTradeNo": "1240838324973731840",
  "sign": "7A5713DCD82F35417222999E634BED65",
  "trade_type": "JSAPI",
  "return_msg": "OK",
  "result_code": "SUCCESS",
  "mch_id": "1527207671",
  "return_code": "SUCCESS",
  "prepay_id": "wx20111131969790bf2a4666f81175548500"
     * 
     * 
     * 
     * **/ 
     let param = {
        timeStamp: data.timeStamp,
        nonceStr: data.nonce_str,
        package: `prepay_id=${data.prepay_id}`,
        signType: 'MD5',
        paySign: data.sign,
     }

     console.log(param);


  //  var timeStamp = Date.parse(new Date()).toString();
   // 生成随机字符串
  //  let nonceStr = Math.random().toString(36).substr(2);
  let that = this;
   wx.requestPayment({
     ...param,
     success(res) { 
         console.log(res,"支付结果--------------------------");
         that.getOrder()
         
        if (res.errMsg =='requestPayment:ok'){
          
          
             


         }


         wx.navigateTo({ 
          url:'/pages/orderList/orderList?checked='+1,
        })
     },
     fail(res) { 
         console.log(res,"失败-------------------")
        //如果子在输入密码的时候点击返回，那么会走失败回调函数
        //
        wx.navigateTo({
          url:'/pages/orderList/orderList?checked='+1,
        })
         
     }
   })
 },
    


    //关闭弹窗
    //点击空白关闭弹窗
    onClose(){
      this.setData({ show: false });
    },


    //跳转到评价页面
    toEvaluatePage(e){
        let  idx = e.currentTarget.dataset.idx;
        let good = this.data.selectItem;
        let details = good.details;
        let detail = details[idx];
        detail = JSON.stringify(detail);
        wx.navigateTo({
          url:`/pages/evaluate/evaluate?good=${detail}&merchantId=${good.merchantId}`,
        })

        this.onClose();
        
    },


    // 去评价，打开弹窗
    toEvaluate(e){
          let goods = e.currentTarget.dataset.goods;
          console.log(goods);
          this.setData({
             show:true,
             selectItem:goods
          })
          console.log("去评价");
    },

      // 延长收货
      extendDate1(e){
        console.log(e.currentTarget.dataset)
        let dataset = e.currentTarget.dataset;
        let id = dataset.id;
        let version=dataset.version;
        extendDate2(id,version);
     

    },


    // 确认收货
    confirmGetGoods1(e){
      let that =this;
      console.log(e.currentTarget.dataset);
      let dataset = e.currentTarget.dataset;
      let id = dataset.id;
      let version=dataset.version;
      confirmGetGoods2(id,version,function(){
          let flag = that.data.flag;
          flag = parseInt(flag);
          that.getOrder(flag);
      });
    },


      // 进入订单详情
     toDetail(e){
         console.log(e.currentTarget.dataset.order);
         let index = e.currentTarget.dataset.order;
          //获取到当前订单
         let order = this.data.allOrder[index];
         console.log(order);
         //如果是售后的话跳转到售后详情，如果是
         //其他类型的话跳转到订单详情
         
        //  if(order.isAbnormal == 0){
        //       //跳转到售后页面
        //       wx.navigateTo({
        //         url:'/pages/afterSaleDetail/afterSaleDetail?orderId='+order.details[0].orderId
        //       })
        //  }else{
              //跳转到详情页面
              order =JSON.stringify(order);
              wx.navigateTo({
                url: '/pages/orderDetail/orderDetail?orderDetail='+order,
              })
        //  }

     },

     delOrder(e){
         let orderId = e.currentTarget.dataset.orderid;
         console.log(orderId);
         let data = {
            openId:wx.getStorageSync("loginInfo").openid,
            ids:[]
         }

         data.ids.push(orderId);
         delOrder(data).then(res=>{
            console.log(res);
            if(res.statusCode == 200){
                if (res.data.code == 200) {
                  wx.showToast({
                    title: '删除成功',
                  })

                  // 刷新页面
                  this.getOrder(this.data.flag);
                } else {
                  wx.showToast({
                    title: "服务器错误，删除失败",
                    icon:'none'
                  })
                }
            }else{
                wx.showToast({
                  title: '网络错误，请重试...',
                  icon:'none'
                })
            }
         })
     },







      getOrder(flag1){
        console.log("调用过来getorder 接口",flag)
        let flag = this.data.flag;
        // 根据flag 的值发送不同的请求，获取不同类型的订单
        let data = {
          openId:wx.getStorageSync('loginInfo').openid,
          currentPage:1,
          pageSize:10
        }
        if(flag == 'nul'){
            // status 不用填
            // data.isAbnormal = 0;售后中的订单
        }else if(flag == 6){

            //如果传这个值，那么查询的是售后订单，
            // 如果不传递这个值那么查询的是普通的各种状态的订单列表
            data.isAbnormal = 0;
        }else{
            flag = parseInt(flag);
            data.status = flag
        }

        getOrder(data).then(res => {
          console.log(res);
          // 获取allOrder
          let allOrder = res.data.data.rows||[];
          // 判断是不是null ，如果是null 那么会弹出提示
          // 并且返回false
          // let result = app.isNullThenShowToast(allOrder);
          // console.log(result, "------------")
          // if(result == false)return;
          // 遍历allorder
          if(allOrder.length<1)return;
          allOrder = this.getNewAllOrder(allOrder);
          

          // 遍历完成后allOrder 已经被改变了
          this.setData({ 
             allOrder
          })
          console.log(allOrder);
        })
      },


        // 这个方法用来过滤之前的specName 让这个specname 
        // 变成数组的形式
      getNewAllOrder(allOrder){
        allOrder.forEach(item => {
          let details = item.details;
            //遍历detail
          details.forEach(ite => {
            //获取specName
            let specName = ite.specName;
            specName = JSON.parse(specName);
            //遍历specName
            let newSpecName = [];
            for (let key in specName) {
              // console.log(specName[key]);
              newSpecName.push(specName[key])
            }
            // 把new specName 放回detail中
            ite.specName = newSpecName;
          })
          //detail 已经被改变了把details 放回 item 中
          item.details = details;
        })


        return allOrder;
      },

      toStore(e){
          console.log(e.currentTarget.dataset.id);
          let merchantId = e.currentTarget.dataset.id;
          wx.navigateTo({
            url: '/pages/shop/shop?id='+merchantId,
          })
      },

      // 上拉加载更多
      getMore(){
        /**
         * 查询实体类(OrderQueryObject)
           openId;"微信用户唯一标识"
           status;"订单状态",
           notes = "null/全部,0待付款/1待发货/2待收货/3待评价
           /4交易成功/5交易关闭/6售后中 "
         * 
         * 
         * **/ 
          console.log("上拉加载更多");
          let data = {
            openId: wx.getStorageSync('loginInfo').openid,
            currentPage:this.data.currentPage,//当前页码
            pageSize:10 //每页显示的条数
          }
          let flag = this.data.flag;
          if(flag == 'nul'){
              // 不需要传status
          }else{
             flag = parseInt(flag);
             data.status = flag 
          }
          getOrder(data).then(res=>{
              console.log(res);
              if(res.data.code == 200){
                    // 获取到想要的数组
                    let data = res.data.data.rows;
                    // 判断是不是null
                    let result = app.isNullThenShowToast(data);
                    if(result==false)return;
                    // 改变specname
                    data = this.getNewAllOrder(data);
                    let allOrder = this.data.allOrder;
                    allOrder = allOrder.concat(data);
                    this.setData({
                        currentPage:++this.data.currentPage,
                        allOrder
                    })

                    console.log("当前页码"+this.data.currentPage);
              }else{
                  wx.showToast({
                    title:"服务器错误",
                    icon:'none'
                  })
              }
          })
      }



  },



/**
 * 组件生命周期的特点
 * 1 进入的时候会触发几个生命周期
 * 2 离开这个页面的时候会触发 detache 生命周期
 * 3 从当前页面跳转到其他页面不会触发生命周期
 * 4 再次回来的时候也不会触发生命周期
 * ***/ 

pageLifetimes: {
  show:function(){
    //页面被展示
    console.log("组件内调用onshow 方法")
    this.getOrder(this.data.flag);
  },
  hide: function() {
    // 页面被隐藏
  },
  resize: function(size) {
    // 页面尺寸变化
  }
},



   lifetimes: {
   
      created() {
        console.log("created在组件实例刚刚被创建时执行")
      },
      attached() {
        console.log("attached在组件实例进入页面节点树时执行",this.data.flag);
        this.getOrder(this.data.flag);
       
      },
      ready() {
        console.log("ready在组件在视图层布局完成后执行")
      },
      moved() {
        console.log("moved在组件实例被移动到节点树另一个位置时执行")
      },
      detached() {
        console.log("detached在组件实例被从页面节点树移除时执行")
      },
      error() {
        console.log("error每当组件方法抛出错误时执行")
      }
  },



})
